package com.example.springbootstartermqttprovider.yinhang;

import java.security.SecureRandom;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

public class UniqueIdGenerator {
    // 包含数字、大小写字母的字符池（排除易混淆字符）
    private static final String CHAR_POOL =
            "23456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjklmnpqrstuvwxyz";
    private static final int ID_LENGTH = 15;

    // 使用ThreadLocal确保线程安全
    private static final ThreadLocal<SecureRandom> randomHolder =
            ThreadLocal.withInitial(() -> {
                try {
                    return SecureRandom.getInstanceStrong();
                } catch (Exception e) {
                    throw new RuntimeException("Failed to get SecureRandom instance", e);
                }
            });

    public static String generateUniqueId() {
        // 将字符池转为List以便使用洗牌算法
        List<Character> chars = CHAR_POOL.chars()
                .mapToObj(c -> (char) c)
                .collect(Collectors.toList());

        // 洗牌增加随机性
        Collections.shuffle(chars, randomHolder.get());

        // 生成随机字符串
        return randomHolder.get()
                .ints(ID_LENGTH, 0, chars.size())
                .mapToObj(i -> String.valueOf(chars.get(i)))
                .collect(Collectors.joining());
    }

    // 防止实例化
    private UniqueIdGenerator() {}
}